package com.hk.utils;

import com.alibaba.fastjson.JSONObject;
import com.hk.model.Admin;
import com.hk.model.vo.Result;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: zhe
 * @Date: 2021/6/22 10:59
 * @Statement: Filter过滤器
 */
@WebFilter("/*")
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
//        获取登录信息
        Admin admin = (Admin) req.getSession().getAttribute("admin");
//        获取当前请求路径
        String uri = req.getRequestURI();
//        System.out.println("获取的登录信息："+admin);
//        System.out.println("获取当前请求路径："+uri);
        if (admin != null || uri.equals("/")) {
//            放行
            chain.doFilter(req, resp);
        } else {
            String[] split = uri.split("/");
//            将分割后的路径放入集合当中
            List<String> urlList = new ArrayList<>();
            for (String s : split) {
                urlList.add(s);
            }
//            分割的第一个为"",可不作为判断依据
//            boolean remove = urlList.remove("");
//            System.out.println("删除状态："+remove);
//            不拦截的
            String[] str = {"css","js","images","img","html","lib","fonts","login.html","tologin","index.html","welcome.html","loginAdmin"};
//            循环判断是否拦截此请求
            boolean bo = false;
            for (String s : urlList) {
                for (String s1 : str) {
                    if (s.equals(s1)) {
//                        放行
                        chain.doFilter(req,resp);
                        bo = true;
                        break;
                    }
                }
                if (bo) {
                    break;
                }
            }
            if (!bo) {
                PrintWriter out = resp.getWriter();
                out.write(JSONObject.toJSONString(new Result(0,"isLogin")));
                out.flush();
                out.close();
            }
        }

    }

    @Override
    public void destroy() {

    }
}
